package server

import (
	"fmt"
	"github.com/patrickmn/go-cache"
	"log"
	"quantization_trading/src/models"
	"quantization_trading/src/mycache"
	"quantization_trading/src/server/ws"
	"quantization_trading/src/util"
)

//初始化价格
func StartPrice()  {
	price_list , err := models.FindAllPrice()
	if err != nil{
		log.Println("启动价格模块异常")
	}else {
		for _,price := range price_list{
			sub := ws.NewSubPrice(price.Exchange, price.ContractType, price.Symbol)
			key := fmt.Sprintf("%s_%s_%s_price", price.Exchange, price.ContractType, price.Symbol)
			err := sub.SubscribePrice()
			if err != nil{
				log.Printf("订阅%s失败，失败原因：%s\n",price.Symbol,err)
			}else {
				log.Printf("订阅%s成功\n",price.Symbol)
				mycache.PriceCache.Set(key,sub,cache.NoExpiration)
			}
		}
	}
}

//添加订阅价格
func AddPrice(price models.Price) int {
	key := fmt.Sprintf("%s_%s_%s_price", price.Exchange, price.ContractType, price.Symbol)
	if _, found := mycache.PriceCache.Get(key); found {
		return util.SUB_HAVE_PRICE
	}else {
		return SubPrice(price)
	}
}

//订阅价格
func SubPrice(price models.Price) int {
	sub := ws.NewSubPrice(price.Exchange ,price.ContractType, price.Symbol)
	key := fmt.Sprintf("%s_%s_%s_price", price.Exchange, price.ContractType, price.Symbol)
	err := sub.SubscribePrice()
	if err != nil{
		return util.SUB_ERROR_PRICE
	}else {
		mycache.PriceCache.Set(key,sub,cache.NoExpiration)
		//保存数据
		return models.AddPrice(&price)
	}
}

// 取消订阅价格
func UnSubPrice(price models.Price) int {
	key := fmt.Sprintf("%s_%s_%s_price", price.Exchange, price.ContractType, price.Symbol)
	var sub ws.SubscribePriceStruct
	if x, found := mycache.PriceCache.Get(key); found {
		sub = x.(ws.SubscribePriceStruct)
		sub.UnSubscribePrice()
		mycache.PriceCache.Delete(key)
		return models.DelPrice(&price)
	}else {
		return util.UNSUB_ERROR_PRICE
	}
}

